#include "ResultSet.h"
#include "SqlResult.h"
#include "Database.h"

LIBDBC_BEGIN_NAMESPACE

ResultSet::ResultSet(IDatabase* pCon, SqlResult * pRes)
{
	_result = pRes;
	_connection = pCon;
	if (_result)
	{
		_result->setConnection(_connection);
	}
}


ResultSet::~ResultSet()
{
	if (_connection && _connection->hasResultSet(this))
	{
		((Database*)_connection)->removeFromResultSetWithoutDeletion(this);
	}

	if (_result)
		delete _result;
}

bool ResultSet::next()
{
	if (_result)
	{
		return _result->next();
	}

	return false;
}

unsigned int ResultSet::getColumnCount()
{
	if (!_result) return 0;
	return _result->getColumnCount();
}

IResultSetMetaData* ResultSet::getResultSetMetaData()
{
	if (!_result) return 0;
	return _result->getResultSetMetaData();
}

int ResultSet::getInt(int field)
{
	if (!_result) return 0;
	return _result->getInt(field);
}

long ResultSet::getLong(int field)
{
	if (!_result) return 0L;
	return _result->getLong(field);
}

double ResultSet::getDouble(int field)
{
	if (!_result) return 0.0;
	return _result->getDouble(field);
}

char* ResultSet::getString(int field, char* buffer, int len)
{
	if (!_result) return "";
	return _result->getString(field, buffer, len);
}

bool ResultSet::getInt(int field, int* pValue)
{
	if (!_result)
	{
		_errorcode = -1;
		return false;
	}
	bool bok = _result->getInt(field, pValue);
	_errorcode = bok ? _result->getLastErrorCode() : 0;
	return bok;
}

bool ResultSet::getLong(int field, long* pValue)
{
	if (!_result)
	{
		_errorcode = -1;
		return false;
	}
	bool bok = _result->getLong(field, pValue);
	_errorcode = bok ? _result->getLastErrorCode() : 0;
	return bok;
}

bool ResultSet::getDouble(int field, double* pValue)
{
	if (!_result)
	{
		_errorcode = -1;
		return false;
	}
	bool bok = _result->getDouble(field, pValue);
	_errorcode = bok ? _result->getLastErrorCode() : 0;
	return bok;
}

bool ResultSet::getStringExt(int field, char* buffer, int len)
{
	if (!_result) {
		_errorcode = -1;
		return false;
	}
	bool bok = _result->getStringExt(field, buffer, len);
	_errorcode = bok ? _result->getLastErrorCode() : 0;
	return bok;
}

bool ResultSet::getBinaryLength(int field, unsigned long* len)
{
	if (!_result)
	{
		_errorcode = -1;
		return false;
	}

	bool bok = _result->getBinaryLength(field, len);
	_errorcode = bok ? _result->getLastErrorCode() : 0;
	return bok;
}

bool ResultSet::getBinary(int field, unsigned char* pBuffer, int buflen)
{
	if (!_result)
	{
		_errorcode = -1;
		return false;
	}

	bool bok = _result->getBinary(field, pBuffer, buflen);
	_errorcode = bok ? _result->getLastErrorCode() : 0;
	return bok;
}


LIBDBC_END_NAMESPACE